package com.tsd.jxc.stock.controller;

import com.alibaba.fastjson.JSON;
import com.tsd.common.controller.BaseController;
import com.tsd.core.annotation.CheckBind;
import com.tsd.core.annotation.DataPermission;
import com.tsd.core.datasource.DataSourceContextHolder;
import com.tsd.core.utils.HlpUtils;
import com.tsd.core.utils.ListUtil;
import com.tsd.core.vo.ErrorCode;
import com.tsd.core.vo.HlpException;
import com.tsd.core.vo.HttpResult;
import com.tsd.core.vo.PageBean;
import com.tsd.jxc.setting.service.JxcSettingService;
import com.tsd.jxc.stock.entity.JxcStockInventoryExt;
import com.tsd.jxc.stock.job.JxcStockJob;
import com.tsd.jxc.stock.service.JxcStockInventoryService;
import com.tsd.jxc.utils.JxcAutoApprovalUtil;
import com.tsd.jxc.vo.PrintVo;
import com.tsd.system.entity.SysUser;
import com.tsd.system.entity.SysUserExt;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.*;

/**
 * 描述：JxcStockInventory盘点信息 控制层
 *
 * @author Hillpool
 * @date 2022/07/29 15:06:33
 */
@Controller
@Scope("prototype")
@RequestMapping("/api/v2")
@Api(tags = "进销存-盘点信息", description = "盘点信息的API描述")
public class JxcStockInventoryController extends BaseController {

    @Resource
    private JxcStockInventoryService jxcStockInventoryService;
    @Resource
    private JxcStockJob jxcStockJob;
    @Resource
    private JxcSettingService jxcSettingService;

    @ApiOperation(value = "根据sid获取盘点信息", notes = "根据sid获取盘点信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sid", value = "盘点信息sid", required = true, dataType = "string", paramType = "form")
    })
    @ResponseBody
    @RequestMapping(value = "/getJxcStockInventoryBySid.action", method = RequestMethod.POST)
    public HttpResult<Object> getJxcStockInventoryBySid() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            Map<String, Object> map = super.getParams(request);
            String sid = HlpUtils.getString(map, "sid");
            super.checkEmpty(sid, "请提供参数sid");
            JxcStockInventoryExt inventoryExt = jxcStockInventoryService.queryBySid(sid);
            hr.setData(inventoryExt);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "根据id删除盘点信息", notes = "根据id删除盘点信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sids", value = "盘点信息sids", required = true, dataType = "string", paramType = "form")
    })
    @ResponseBody
    @RequestMapping(value = "/deleteJxcStockInventorys.action", method = RequestMethod.POST)
    public HttpResult<String> deleteJxcStockInventorys() {
        HttpResult<String> hr = new HttpResult<>();
        try {
            SysUser opUser = super.getSysUser();
            Map<String, Object> map = super.getParams(request);
            Object sids = map.get("sids");
            super.checkEmpty(sids, "请提供参数sids");
            List<String> list = JSON.parseArray(JSON.toJSONString(sids), String.class);
            jxcStockInventoryService.deleteJxcStockInventorys(list, opUser);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }


    @ApiOperation(value = "保存盘点信息", notes = "保存盘点信息，具有id值则更新，没有id值则新增")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "obj", value = "盘点信息", required = true, paramType = "body", dataType = "JxcStockInventory")
    })
    @ResponseBody
    @RequestMapping(value = "/saveJxcStockInventory.action", method = RequestMethod.POST)
    @CheckBind(person = true)
    public HttpResult<Object> saveJxcStockInventory() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            SysUserExt opUser = super.getSysUser();
            Map<String, Object> map = super.getParams(request);
            String json = JSON.toJSONString(map);
            JxcStockInventoryExt inventoryExt = JSON.parseObject(json, JxcStockInventoryExt.class);
            jxcStockInventoryService.saveJxcStockInventory(inventoryExt, opUser);
            // 判断是否自动审核
            JxcAutoApprovalUtil.autoApproval("auto_approval_stock_inventory", () -> {
                jxcStockInventoryService.changeJxcStockInventoryAuditState(Collections.singletonList(inventoryExt.getSid()), 1, opUser);
            });
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "分页查询盘点信息", notes = "分页查询盘点信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "名称", required = false, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "pageNo", value = "页码", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "pageSize", value = "页大小，每页记录数", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "sorts", value = "排序设置，方式['property1 desc','property2']", required = false, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "totalRows", value = "总记录数，为了减少统计总记录数，一般从第二页开始前端提供totalRows", required = false, dataType = "int", paramType = "form")
    })
    @ResponseBody
    @RequestMapping(value = "/findJxcStockInventorys.action", method = RequestMethod.POST)
    @DataPermission(code = "stockInventory")
    public HttpResult<Object> findJxcStockInventorys() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            Map<String, Object> map = super.getParams(request);
            Map<String, Object> params = super.getDataPermissionParams();
            HlpUtils.copyIntegerValue(map, params, "dr", "dr", false, 0);
            HlpUtils.copyStringValue(map, params, "code", "code", false, false);
            HlpUtils.copyStringValue(map, params, "state", "state", false, false);
            HlpUtils.copyStringValue(map, params, "warehouse_sid", "warehouse_sid", false, false);
            HlpUtils.copyStringValue(map, params, "search_value", "search_value", false, true);
            HlpUtils.copyDateRangeValue(map, params, "check_date", false);
            PageBean page = new PageBean(map);
            List<JxcStockInventoryExt> list = jxcStockInventoryService.findJxcStockInventorys(params, page);
            hr.setData(list);
            hr.setPage(page);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "根据提供信息，分页查询盘点信息", notes = "根据提供信息，分页查询盘点信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "名称", required = false, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "pageNo", value = "页码", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "pageSize", value = "页大小，每页记录数", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "sorts", value = "排序设置，方式['property1 desc','property2']", required = false, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "totalRows", value = "总记录数，为了减少统计总记录数，一般从第二页开始前端提供totalRows", required = false, dataType = "int", paramType = "form")
    })
    @ResponseBody
    @RequestMapping(value = "/selectInventoryByPage.action", method = RequestMethod.POST)
    public HttpResult<List<JxcStockInventoryExt>> selectInventoryByPage() {
        HttpResult<List<JxcStockInventoryExt>> hr = new HttpResult<>();
        try {
            Map<String, Object> map = super.getParams(request);
            Map<String, Object> params = new HashMap<>(8);
            HlpUtils.copyIntegerValue(map, params, "dr", "dr", false, 0);
            HlpUtils.copyStringValue(map, params, "search_value", "search_value", false, true);
            HlpUtils.copyStringValue(map, params, "sid", "sid", false, false);
            HlpUtils.copyStringValue(map, params, "code", "code", false, false);
            HlpUtils.copyStringValue(map, params, "warehouse_sid", "warehouse_sid", false, false);
            HlpUtils.copyStringValue(map, params, "begin_date", "begin_date", false, false);
            HlpUtils.copyStringValue(map, params, "end_date", "end_date", false, false);
            HlpUtils.copyStringValue(map, params, "curState", "state", false, false);
            PageBean page = new PageBean(map);
            List<JxcStockInventoryExt> list = jxcStockInventoryService.selectInventoryByPage(params, page);
            hr.setData(list);
            hr.setPage(page);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "审核/反审核盘点单", notes = "审核/反审核盘点")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sid_list", value = "盘点单列表的sid", required = true, dataType = "List", paramType = "object"),
            @ApiImplicitParam(name = "state", value = "审核为1，反审核为0", required = true, dataType = "Integer", paramType = "integer"),
    })
    @ResponseBody
    @RequestMapping(value = "/changeJxcStockInventoryAuditState.action", method = RequestMethod.POST)
    @CheckBind(person = true)
    public HttpResult<String> changeJxcStockInventoryAuditState() {
        HttpResult<String> hr = new HttpResult<>();
        try {
            SysUserExt opUser = super.getSysUser();
            Map<String, Object> map = super.getParams(request);
            Integer state = HlpUtils.getInteger(map, "state");
            super.checkEmpty(state, "请提供参数：state");
            if (!Arrays.asList(1, -1).contains(state)) {
                throw new HlpException("state值错误：1-审核、-1-反审核");
            }
            List<String> sidList = super.getParamsList(map, "sid_list", String.class, true);
            jxcStockInventoryService.changeJxcStockInventoryAuditState(sidList, state, opUser);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "复核盘点单", notes = "复核盘点信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "inventory_sid", value = "盘点单的sid", required = true, dataType = "List", paramType = "object"),
            @ApiImplicitParam(name = "state", value = "复核为2,审核为1，反审核为0", required = true, dataType = "Integer", paramType = "integer"),
    })
    @ResponseBody
    @RequestMapping(value = "/saveJxcStockInventory4Review.action", method = RequestMethod.POST)
    @CheckBind(person = true)
    public HttpResult<String> saveJxcStockInventory4Review() {
        HttpResult<String> hr = new HttpResult<>();
        try {
            SysUserExt opUser = super.getSysUser();
            JxcStockInventoryExt inventoryExt = super.getParams(request, JxcStockInventoryExt.class);
            jxcStockInventoryService.saveJxcStockInventory4Review(inventoryExt, opUser);

//            jxcStockJob.addAccountSet2PriorityQueue(DataSourceContextHolder.getDataSourceType());
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "盘点单更新库存", notes = "盘点单更新库存")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "inventory_sid", value = "盘点单的sid", required = true, dataType = "List", paramType = "object"),
    })
    @ResponseBody
    @RequestMapping(value = "/saveJxcStockInventory4UpdateStock.action", method = RequestMethod.POST)
    public HttpResult<String> saveJxcStockInventory4UpdateStock() {
        HttpResult<String> hr = new HttpResult<>();
        try {
            SysUserExt opUser = super.getSysUser();
            JxcStockInventoryExt inventoryExt = super.getParams(request, JxcStockInventoryExt.class);
            jxcStockInventoryService.saveJxcStockInventory4UpdateStock(inventoryExt, opUser);

            jxcStockJob.addAccountSet2PriorityQueue(DataSourceContextHolder.getDataSourceType());
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "打印获取盘点单数据", notes = "打印获取盘点单数据")
    @ResponseBody
    @RequestMapping(value = "/queryJxcStockInventoryData4Print.action", method = RequestMethod.POST)
    public HttpResult<Object> queryJxcStockInventoryData4Print() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            SysUserExt opUser = super.getSysUser();
            List<String> sidList = super.getParamsList("sid_list", String.class, true);
            List<JxcStockInventoryExt> list = jxcStockInventoryService.queryJxcStockInventoryData4Print(sidList);
            List<PrintVo> voList = ListUtil.map(list, t -> t.convert2Print(opUser));
            hr.setData(voList);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "生成出入库单", notes = "生成出入库单")
    @ResponseBody
    @RequestMapping(value = "/genJxcStockInventory4InOutBill.action", method = RequestMethod.POST)
    public HttpResult<Object> genJxcStockInventory4InOutBill() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            SysUserExt opUser = super.getSysUser();
            JxcStockInventoryExt inventoryExt = super.getParams(request, JxcStockInventoryExt.class);
            jxcStockInventoryService.genJxcStockInventory4InOutBill(inventoryExt, opUser);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

}
